package com.zs4sdk.activity;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.zs4sdk.common.Extra;
import com.common.library.data.CommonHandle;
import com.common.library.data.EventHandler2Get;
import com.common.library.data.CommonEventHandler.ResultHandlerInEvent;
import com.common.library.data.CommonHandle.HandleMessage;
import com.common.library.entity.JSONResultEntity;
import com.zs4sdk.entity.Zs4GameData;
import com.zs4sdk.entity.LoginJSONResultEntity;
import com.common.library.util.ActivityHelper;
import com.common.library.util.EncryptHelper;
import com.common.library.util.HandlerUtil;
import com.common.library.util.Helper;
import com.common.library.util.NetworkHelper;
import com.common.library.util.ParamsHelper;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * 绑定手机号
 */
@SuppressLint("NewApi")
public class Zs4GameBindSafePhoneActivity extends Zs4GameBaseActivity {

    public static final String TAG = Zs4GameBindSafePhoneActivity.class.getSimpleName();


    // 手机号码输入框
    private EditText mBindPhoneView;
    private EditText mBindMessageTextView;
    private EditText mBindPasswordView;
    private Button mBindRequstVerifyCodeView;
    private Button mBindConfirm;
    private int backSendMsg = 12;

    private TextView  tipTextView;

    private TextView mTxvUpdateDesc;

    // 定义计时器
    private MyCount mSendMessageTimer;
    private String mPhoneNum;
    int PHONE_TYPE1 = 2;//手机号属于未注册
    int PHONE_TYPE2 = 3;//手机号已注册但没有设置密码
    int PHONE_TYPE3 = 4;//手机号已注册已设置密码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(ActivityHelper.getLayoutResId("zs4gamelayout_act_bind_safe_phone"));

        getParams();
        init();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (Helper.isNotNull(mSendMessageTimer)) {
            mSendMessageTimer.cancel();
        }

    }

    /**
     * 获取参数
     */
    private void getParams() {
        Intent intent = this.getIntent();

        if (Helper.isNotNull(intent)) {
            if (intent.hasExtra(Extra.INTENTKEY.BIND_PHONE)) {
                backSendMsg = TYPE_LEFTBTN_BACK;
            }else {
                backSendMsg =  TYPE_LEFTBTN_BACKTOMENU;
            }
        }

    }

    @Override
    protected void init() {
        super.init();

        //输入框部分
        mTxvUpdateDesc = findView(TextView.class, ActivityHelper.getIdResId("zs4gameviewid_mAccountView_act_txv_account"));//当前账号
        mBindPhoneView = findView(EditText.class, ActivityHelper.getIdResId("zs4gameviewid_mAccountView_act_bind_safe_phone"));//手机号输入框
        mBindPasswordView = findView(EditText.class, ActivityHelper.getIdResId("zs4gameviewid_mPasswordView_act_bind_safe_phone_password"));//密码输入框
        mBindMessageTextView = findView(EditText.class, ActivityHelper.getIdResId("zs4gameviewid_mMessageView_act_bind_safe_phone_textmessage"));//验证码输入框
        mBindRequstVerifyCodeView = findView(Button.class, ActivityHelper.getIdResId("zs4gameviewid_mMessageBtn_act_bind_safe_phone_request"));//获取短信验证码按钮
        tipTextView = findView(TextView.class, ActivityHelper.getIdResId("zs4gameviewid_textview_retrivepassword_phone"));//点击按钮的提示信息
        mBindConfirm = findView(Button.class, ActivityHelper.getIdResId("zs4gameviewid_mCommitView_act_bind_safe_phone_confirm"));//确定

        mBindPhoneView.addTextChangedListener(mTextWatcher);
        setTopTitle(ActivityHelper.getStringResId("zs4gamestring_title_bind_phone"));
        mTxvUpdateDesc.setText( Zs4GameData.getInstance().getSDKUserInfo().getNickName());

        setViewClickEvent(this, ActivityHelper.getIdResId("zs4gameviewid_mMessageBtn_act_bind_safe_phone_request"),
                ActivityHelper.getIdResId("zs4gameviewid_mCommitView_act_bind_safe_phone_confirm"));
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);

        int id = v.getId();
        // 请求手机短信验证码
        if (ActivityHelper.getIdResId("zs4gameviewid_mMessageBtn_act_bind_safe_phone_request") == id) {
            request4VerifyCode(Extra.VERIFYTYPE.VERIFYTYPE_TEXTMESSAGE);
        }
        // 确定绑定
        else if (ActivityHelper.getIdResId("zs4gameviewid_mCommitView_act_bind_safe_phone_confirm") == id) {
            //更新的最后一步
                updateSafePhoneStepTwo();
        }
    }

    /**
     * 请求短信验证码
     *
     * @param sendmode
     */
    private void request4VerifyCode(String sendmode) {

        String phoneNumb = null;

        phoneNumb = mBindPhoneView.getText().toString().trim();

        if (Helper.isEmpty(phoneNumb)) {
            tipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_phone_num_not_empty"));
            return;
        } else if (!Helper.checkMobile(phoneNumb)) {
            tipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_phone_num_format"));
            return;
        }

        if (NetworkHelper.isNetworkAvailable(Zs4GameBindSafePhoneActivity.this)) {

            // 开启计时器
            mSendMessageTimer = new MyCount(Extra.SDKGAMESTRS.GET_AGAIN, 1000);
            mSendMessageTimer.start();

            ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
            paramList.add(new BasicNameValuePair("mobile", EncryptHelper.encryptByAES(phoneNumb)));

            new EventHandler2Get(
                    Extra.URL.PHONEVERIFYCODE,
                    paramList,
                    ParamsHelper.getUserAgent1(), new ResultHandlerInEvent() {

                @Override
                public void doResultHanler(JSONObject result) throws JSONException {
                    Log.e("phone"," phone result is "+result.toString());
                    Message msg = myHandle.obtainMessage();

                    msg.what = Extra.MessageKey.REQUEST_VERIFY_SUCCESS;
                    msg.obj = result;

                    Bundle bundle = new Bundle();
                    msg.setData(bundle);

                    // 发送消息
                    myHandle.sendMessage(msg);

                }

                @Override
                public void doExceptionHandler() {
                    // TODO Auto-generated method stub

                }
            });

        } else {
            tipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_has_not_network"));
        }
    }
    /***
     * 更新绑定安全手机，第二步 绑定
     */
    private void updateSafePhoneStepTwo() {
        final String phoneNumb = mBindPhoneView.getText().toString().trim();
        String messageText = mBindMessageTextView.getText().toString().trim();
        String password =  mBindPasswordView.getText().toString().trim();

        // 手机号不为空
        if (Helper.isEmpty(phoneNumb)) {
            tipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_phone_num_format"));
            return;
        }//判断手机号码是否正确
        else if (!Helper.checkMobile(phoneNumb)) {
            tipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_phone_num_format"));
            return;
        }//密码不能为空
        else if (Helper.isEmpty(password)) {
            tipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_text_edt_tip_password"));
            return;
        }//密码长度错误
        else if (password.length() < 6||password.length()>12) {
            tipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_password_length"));
            return;
        }
        // 短信验证码不为空
        else if (Helper.isEmpty(messageText)) {
            tipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_phone_message_text_not_empty"));
            return;
        }
        Log.e("phone"," bind phone is "+phoneNumb);
        if (NetworkHelper.isNetworkAvailable(Zs4GameBindSafePhoneActivity.this)) {

            HandlerUtil.sendMessage(myHandle, Extra.MessageKey.SHOWPROCESS);

            ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
        //    paramList.add(new BasicNameValuePair("mobile", EncryptHelper.encryptByAES(phoneNumb)));
            paramList.add(new BasicNameValuePair("account", EncryptHelper.encryptByAES(phoneNumb)));
            paramList.add(new BasicNameValuePair("password", EncryptHelper.encryptByAES(EncryptHelper.md5(password))));
            paramList.add(new BasicNameValuePair("verifycode", EncryptHelper.encryptByAES(messageText)));
        //    Log.e("phone"," bind EncryptHelper.encryptByAES(phoneNumb)) is "+EncryptHelper.encryptByAES(phoneNumb));
            new EventHandler2Get(
                    Extra.URL.UPDATE_SAFE_PHONE,
                    paramList,
                    ParamsHelper.getUserAgent1(), new ResultHandlerInEvent() {

                @Override
                public void doResultHanler(JSONObject result) throws JSONException {
                    HandlerUtil.sendMessage(myHandle, Extra.MessageKey.DISMISSPROCESS);

                    Message msg = myHandle.obtainMessage();

                    msg.what = Extra.MessageKey.UPDATE_SAFE_PHONE_STEP_TWO;
                    msg.obj = result;

                    Bundle bundle = new Bundle();
                    bundle.putString("param1",phoneNumb);
                    msg.setData(bundle);

                    // 发送消息
                    myHandle.sendMessage(msg);

                }

                @Override
                public void doExceptionHandler() {
                    HandlerUtil.sendMessage(myHandle, Extra.MessageKey.DISMISSPROCESS);
                }
            });
        }else {
            tipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_has_not_network"));
        }
    }

    private void getoVerifyPhone(String phoneNumber) {
        if (NetworkHelper.isNetworkAvailable(this)) {
            ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
            paramList.add(new BasicNameValuePair("mobile", EncryptHelper.encryptByAES(phoneNumber)));
            new EventHandler2Get(
                    Extra.URL.VERIFY_PHONE,//      PHONEVERIFYCODE2,
                    paramList,
                    ParamsHelper.getUserAgent1(), new ResultHandlerInEvent() {
                @Override
                public void doResultHanler(JSONObject result) throws JSONException {
                    Message msg = myHandle.obtainMessage();
                    msg.what = Extra.MessageKey.VERIFY_PHONE_REGIDTER_OR_LOGIN;
                    msg.obj = result;
                    Bundle bundle = new Bundle();
                    msg.setData(bundle);
                    // 发送消息
                    myHandle.sendMessage(msg);
                }
                @Override
                public void doExceptionHandler() {
                }
            });
        } else {
            tipTextView.setVisibility(View.VISIBLE);
            tipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_has_not_network"));
            return;
        }
    }

    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//            doButtonChange(s);
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            doButtonChange(s);
        }

        @Override
        public void afterTextChanged(Editable s) {
//            doButtonChange(s);
        }
    };
    private void doButtonChange(CharSequence s){
        if(s.toString().length()==11&&Helper.checkMobile(s.toString())){
            getoVerifyPhone(s.toString());
        }else {
            tipTextView.setText("");
        }

    }

    CommonHandle myHandle = new CommonHandle(Zs4GameBindSafePhoneActivity.this, new HandleMessage() {

        @Override
        public void doHandleMessage(Message msg) {

            if (Extra.MessageKey.REQUEST_VERIFY_SUCCESS == msg.what) {

                LoginJSONResultEntity entity = new LoginJSONResultEntity((JSONObject) msg.obj);

                if(entity.isSuccess()){

                    tipTextView.setText(entity.getDesc());
                }else {
                    tipTextView.setText(entity.getDesc());
                }

            } else if (Extra.MessageKey.BIND_SAFE_PHONE_SUCCESS == msg.what) {

                LoginJSONResultEntity entity = new LoginJSONResultEntity((JSONObject) msg.obj);

                ActivityHelper.showLongToast(entity.getDesc());

                if (entity.isSuccess()) {

                    //返回手机号
                    Intent intent = new Intent();
//                    intent.putExtra(Extra.INTENTKEY.BIND_PHONE, mPhoneNum);
                    setResult(Extra.RESULTCODE.RESULT_BIND_PHONE, intent);
                    finish();
                }
            }
            //绑定结果
            else if (Extra.MessageKey.UPDATE_SAFE_PHONE_STEP_TWO == msg.what) {
                LoginJSONResultEntity entity = new LoginJSONResultEntity((JSONObject) msg.obj);

                if (entity.isSuccess()) {
                    LoginJSONResultEntity entity1 = Zs4GameData.getInstance().getLastLoginedUserInfo();
                    entity1.setLoginType("1");
                    Bundle bundle = msg.getData();
                        if (bundle.containsKey("param1")) {
                            entity1.setMobile(bundle.getString("param1"));
                        }
                    Zs4GameData.getInstance().saveUserLoginInfoForLoginedSuccess(entity1);
                    ActivityHelper.showToast(ActivityHelper.getStringResId("zs4gamestring_text_bind_successed"));
                    backToGame();
                }else {
                    tipTextView.setText(entity.getDesc());
                }
            }

            //判断手机号码状态 注册过还是没有注册过,设置过密码还是没有设置密码
            else if (Extra.MessageKey.VERIFY_PHONE_REGIDTER_OR_LOGIN == msg.what) {
                JSONResultEntity entity = new JSONResultEntity((JSONObject) msg.obj);
                if (entity.getResult() == PHONE_TYPE1) {
                    mBindRequstVerifyCodeView.setClickable(true);
                    mBindConfirm.setClickable(true);
                    tipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_btn_goto_bind_useful_phone"));

                } else if (entity.getResult() == PHONE_TYPE2) {
                    mBindRequstVerifyCodeView.setClickable(false);
                    mBindConfirm.setClickable(false);
                    tipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_btn_goto_bind_usered_phone"));

                } else if (entity.getResult() == PHONE_TYPE3) {
                    mBindRequstVerifyCodeView.setClickable(false);
                    mBindConfirm.setClickable(false);
                    tipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_btn_goto_bind_usered_phone"));
                }else {
                    mBindRequstVerifyCodeView.setClickable(true);
                    mBindConfirm.setClickable(true);
                }
            }
        }
    });

    private void goBackToAccount(){
        //返回手机号
        Intent intent = new Intent();
//        intent.putExtra(Extra.INTENTKEY.BIND_PHONE, mPhoneNum);
        setResult(Extra.RESULTCODE.RESULT_BIND_PHONE, intent);
        finish();
    }


    @Override
    protected int getLeftBtnType() {

        if (getPackageName().concat(Extra.ACTIONKEY.CLOSEACTIVITY_POSTFIX_SLIDETOAST).equals(flag)) {
            return TYPE_LEFTBTN_BACKTOGAME;
        } else {
            return backSendMsg;
        }
    }

    @Override
    protected  int getRightBtnType() {
        return TYPE_RIGHTBTN_INVISIBLE;
    }

    /*定义一个倒计时的内部类*/
    class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            // 还原btn按钮
            mBindRequstVerifyCodeView.setBackgroundDrawable(ActivityHelper.getDrawableByName("zs4gamedraw_conner_red_5_bg"));
            mBindRequstVerifyCodeView.setClickable(true);
            mBindRequstVerifyCodeView.setText(ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_btn_send_message_verify")));
        }


        @Override
        public void onTick(long millisUntilFinished) {
            mBindRequstVerifyCodeView.setText("重新发送("+ millisUntilFinished / 1000 + ")");
            // 设置btn样式
            mBindRequstVerifyCodeView.setBackgroundDrawable(ActivityHelper.getDrawableByName("zs4gamedraw_conner_gray_5_bg"));
            // 设置不可点击
            mBindRequstVerifyCodeView.setClickable(false);
        }
    }
}
